package com.py.credit.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.py.framework.core.rest.support.RestServiceResult;

public class EndPointAccessInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String accessToken = request.getParameter("accessToken");

		if (accessToken == null || accessToken.isEmpty()) {
			// 输出响应信息
			this.printMsg(response, RestServiceResult.CODE_UNKNOW, "accessToken 验证失败");
			return false;
		}
		return true;

	}

	/**
	 * 输出文本
	 * 
	 * @param response
	 * @param code
	 * @param msg
	 * @throws IOException
	 */
	private void printMsg(HttpServletResponse response, int code, String msg) throws IOException {
		// 设置格式为text/json
		response.setContentType("text/json");
		// 设置字符集为'UTF-8'
		response.setCharacterEncoding("UTF-8");

		// 设置返回信息
		RestServiceResult<String> result = new RestServiceResult<String>();
		result.setCode(code);
		result.setMsg(msg);

		PrintWriter out = response.getWriter();
		out.println(JSON.toJSONString(result));
		out.flush();
		out.close();
	}

}
